#include "drscontrol.h"
#include <QTcpSocket>
#include <QMessageBox>
#include <QScrollBar>
#include <QStyleOptionTitleBar>

void DRSControl::on_inputLineEdit_returnPressed( void )
{
	sock = new QTcpSocket(this);
	connect(sock,SIGNAL(readyRead()),this, SLOT(readFromSock()));
	connect(sock, SIGNAL(error(QAbstractSocket::SocketError)),
             this, SLOT(displayError(QAbstractSocket::SocketError)));
	sock->connectToHost(ui.hostLineEdit->text(), 
			 ui.portLineEdit->text().toInt());
	QString sendThis = ui.inputLineEdit->displayText();
	int strLen = sendThis.length();
	qDebug() << sendThis << "its: " << strLen << " long";
	QString x = sendThis;
	x = x.prepend("TX: ");
	ui.recieveTextEdit->append(x + "\n");
	sendThis.append("\n");
	QByteArray ok = sendThis.toLatin1();
	char * text = ok.data();
	sock->write(text,strLen);
	ui.inputLineEdit->clear();
}
void DRSControl::readFromSock()
{
	QDataStream in(sock);
	in.setVersion(QDataStream::Qt_4_0);

	if (blockSize == 0) 
	{
		if (sock->bytesAvailable() < (int)sizeof(quint16))
			return;
		in >> blockSize;
	}
	QScrollBar *bar = ui.recieveTextEdit->verticalScrollBar();
	QByteArray tmpBuffer = sock->readAll();                   
	QString recieveText(tmpBuffer);                           
	recieveText = recieveText.prepend("RX: "); 
	recieveText = recieveText.remove("\r\n",Qt::CaseInsensitive);
	ui.recieveTextEdit->insertPlainText(recieveText);         
	bar->setValue(bar->maximum());                            
}
void DRSControl::displayError(QAbstractSocket::SocketError socketError)
 {
     switch (socketError) {
     case QAbstractSocket::RemoteHostClosedError:
         break;
     case QAbstractSocket::HostNotFoundError:
         QMessageBox::information(this, tr("DRS Control"),
                                  tr("The host was not found. Please check the "
                                     "host name and port settings."));
         break;
     case QAbstractSocket::ConnectionRefusedError:
         QMessageBox::information(this, tr("DRS Control"),
                                  tr("The connection was refused by the peer. "
                                     "Make sure the fortune server is running, "
                                     "and check that the host name and port "
                                     "settings are correct."));
         break;
     default:
         QMessageBox::information(this, tr("DRS Control"),
                                  tr("The following error occurred: %1.")
                                  .arg(sock->errorString()));
     }

 }